// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/functions/macros.h>
#include <pollux/functions/prestosql/json/simd_json_util.h>

namespace kumo::pollux::functions::sparksql {
    /// json_object_keys(jsonString) -> array(string)
    ///
    /// Returns all the keys of the outermost JSON object as an array if a valid
    /// JSON object is given.
    template<typename T>
    struct JsonObjectKeysFunction {
        POLLUX_DEFINE_FUNCTION_TYPES(T);

        MELON_ALWAYS_INLINE bool call(
            out_type<Array<Varchar> > &out,
            const arg_type<Varchar> &json) {
            simdjson::ondemand::document jsonDoc;

            simdjson::padded_string paddedJson(json.data(), json.size());
            // The result is NULL if the given string is not a valid JSON string.
            if (simdjsonParse(paddedJson).get(jsonDoc)) {
                return false;
            }

            // The result is NULL if the given string is not a valid JSON string.
            if (isFatal(jsonDoc.type().error())) {
                return false;
            }

            // The result is NULL if the given string is not a JSON object string.
            if (jsonDoc.type() != simdjson::ondemand::json_type::object) {
                return false;
            }

            simdjson::ondemand::object jsonObject;
            // The result is NULL if the given string is not a valid JSON object string.
            if (jsonDoc.get_object().get(jsonObject)) {
                return false;
            }

            for (auto field: jsonObject) {
                if (isFatal(field.error())) {
                    // On-Demand only fully validates the values used and the structure
                    // leading to it.
                    return false;
                }
                out.add_item().copy_from(std::string_view(field.unescaped_key()));
            }
            return true;
        }

    private:
        // TODO: After upgrade simdjson v3.12.3, we could replace with simdjson
        // function relevant simdjson function:
        // https://github.com/simdjson/simdjson/blob/master/include/simdjson/error-inl.h#L10-L12
        bool isFatal(simdjson::error_code error) noexcept {
            // Indicates the document is not valid JSON.
            return error == simdjson::error_code::TAPE_ERROR ||
                   error == simdjson::error_code::INCOMPLETE_ARRAY_OR_OBJECT;
        }
    };
} // namespace kumo::pollux::functions::sparksql
